package com.irdstudio.rsp.drools.filter;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;

public class GzipRequestWrapper extends HttpServletRequestWrapper {
    private HttpServletRequest request;

    public GzipRequestWrapper(HttpServletRequest request) {
        super(request);
        this.request = request;
    }

    public ServletInputStream getInputStream() throws IOException {
        byte[] bytes = IOUtils.toByteArray(this.request.getInputStream());
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        final GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream);
        ServletInputStream newStream = new ServletInputStream() {
            public int read() throws IOException {
                return gzipInputStream.read();
            }
        };
        return newStream;
    }
}